package utils

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func FileExists(filename string) bool {
	info, err := os.Stat(filename)
	if os.IsNotExist(err) {
		return false
	}
	return !info.IsDir()
}

func ReadFile(filename string, p ...string) ([]byte, error) {

	var filePath string

	if !(strings.HasSuffix(filename, ".js") || strings.HasSuffix(filename, ".json")) {
		filename = filename + ".js"
	}

	cwd, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	if len(p) == 1 {
		cwd = cwd + "/" + p[0]
	} else {
		cwd = cwd + "/components"
	}

	if FileExists(filename) {
		filePath = filename
	} else {
		filePath = filepath.Join(cwd, filename)
	}

	filePath = filepath.Clean(filePath)

	content, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err

	}

	return content, nil

}
